package com.asj.vivo.lock.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * 下载监听器
 * */
public class DownloadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(downloadId));

        if (cursor.moveToFirst()) {
            int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int filePathIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

            if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(statusIndex)) {
                String filePath = cursor.getString(filePathIndex);
            }
        }

        cursor.close();
    }

    private void installApk(Context context, Uri apkUri) {
        // 获取SD卡的根路径
        String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
        // 设置Apk文件的保存路径
        String apkSavePath = sdcardRoot + apkUri;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(apkSavePath);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}